package library

import (
	"os"
	"path/filepath"
	"plugin"
	"runtime"
	"strings"

	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/os/glog"
)

func InitLog() {
	glog.SetDefaultLogger(g.Log())
	glog.SetDebug(false)
	glog.SetStack(false)
	glog.SetFlags(glog.F_TIME_STD | glog.F_FILE_SHORT)
}

// GetCurProjectDir 获取当前项目路径, 不包含最后的 "/"
func GetCurProjectDir() string {
	return GetProjectDir("collect-log")
}

// GetProjectDir 获取项目路径, 不包含最后的 "/"
func GetProjectDir(projectName string) string {
	projectDir, _ := os.Getwd()
	splitIndex := strings.LastIndex(projectDir, projectName)
	return projectDir[:splitIndex+len(projectName)]
}

// InitEnc2Dec 初始化加/解密
func InitEnc2Dec() {
	projectDir := GetCurProjectDir()
	soPath := ""
	// 初始化解密工具
	switch runtime.GOOS {
	case "linux":
		soPath = filepath.Join("/usr/lib64", "enc2dec.so")
	case "darwin":
		soPath = filepath.Join(projectDir, "library", "enc2dec.so")
	default:
		DecFn = func(in string) (out string) {
			return
		}
		return
	}

	f, err := plugin.Open(soPath)
	if err != nil {
		glog.Panic("plugin.Open is failed, err: ", err)
	}

	dec, err := f.Lookup("Dec")
	if err != nil {
		glog.Panic("f.Lookup(\"Dec\") is failed, err: ", err)
	}

	DecFn = func(in string) string {
		return dec.(func(string, ...string) string)(in, "collect-log")
	}
}
